package com.ssyx.helper;

import com.ssyx.constant.GlobalConstant;
import com.ssyx.model.acl.Permission;
import com.ssyx.model.acl.RolePermission;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: ssyx-parent
 * @className: PermissionHelper
 * @description: 权限数据构建菜单数据
 * @data: 2024/3/7 15:08
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
public class PermissionHelper {
	/**
	 * 使用递归方法建菜单
	 */
	public static List<Permission> bulid(List<Permission> treeNodes, List<RolePermission> rolePermissions) {
		List<Permission> trees = new ArrayList<>();
		for (Permission treeNode : treeNodes) {
			if (treeNode.getPid().equals(GlobalConstant.LONG_ZERO)) {
				treeNode.setLevel(GlobalConstant.INTEGER_ONE);
				trees.add(findChildren(treeNode, treeNodes, rolePermissions));
			}
		}
		return trees;
	}
	
	/**
	 * 递归查找子节点
	 */
	public static Permission findChildren(Permission treeNode, List<Permission> treeNodes,
	                                      List<RolePermission> rolePermissions) {
		treeNode.setChildren(new ArrayList<>());
		for (Permission it : treeNodes) {
			if (rolePermissions != null) {
				for (RolePermission rolePermission : rolePermissions) {
					if (rolePermission.getPermissionId().longValue() == it.getId().longValue()) {
						it.setSelect(true);
						break;
					}
				}
			}
			if (treeNode.getId().longValue() == it.getPid().longValue()) {
				int level = treeNode.getLevel() + GlobalConstant.INTEGER_ONE;
				it.setLevel(level);
				if (treeNode.getChildren() == null) {
					treeNode.setChildren(new ArrayList<>());
				}
				treeNode.getChildren().add(findChildren(it, treeNodes, rolePermissions));
			}
		}
		return treeNode;
	}
}
